//
//  FileHelper.swift
//  eBooks
//
//  Created by JunMing on 2019/11/4.
//  Copyright © 2019 赵俊明. All rights reserved.
//

import UIKit

class FileHelper: NSObject {
    static func deleteFile(_ name:String) {
        let sourceUrl = Tools.documentPath()!+"/"+name
        let fileManger = FileManager.default
        do{
            try fileManger.removeItem(atPath: sourceUrl)
            print("Success to remove file.")
        }catch{
            print("Failed to remove file.")
        }
    }
    
    static func getFileFromDir(_ dir:String,_ subffix:String) -> Array<String> {
        var nameArr = [String]()
        let manager = FileManager.default
        if let array = try? manager.contentsOfDirectory(atPath: dir) {
            for name in array {
                if name.hasSuffix(subffix) || name.hasSuffix("pdf") || name.hasSuffix("txt") {
                    nameArr.append(name)
                }
            }
        }
        return nameArr
    }
    
//    /// 遍历docu下文件生成model
//    static func homeModels() ->Array<Model> {
//        let nameArr = getFileFromDir(Tools.documentPath()!, "epub")
//        var modelArr = [Model]()
//        for name in nameArr {
//            if let bookSize = EBookDefault.readStringByKey("size"+name) {
//                let model = Model(name,bookSize)
//                model.isdel = false
//                SQLHelper.share.updateModelData(model)
//                modelArr.append(model)
//            }else {
//                let bookSize = getFilesBytesByPath(Tools.documentPath()!+"/"+name);
//                let model = Model(name,bookSize)
//                model.isdel = false
//                modelArr.append(model)
//                SQLHelper.share.updateModelData(model)
//                EBookDefault.setString(bookSize, "size"+name)
//            }
//        }
//        return modelArr
//    }
    
    /// 根据单个文件名生成model
    static func singleModel(_ name:String) ->Model {
        if let bookSize = EBookDefault.readStringByKey("size"+name) {
            let model = Model(name,bookSize)
            model.isdel = false
            model.date = String(format: "%f", arguments: [Date.currentTime])
            return model
        }else {
            let bookSize = getFilesBytesByPath(Tools.documentPath()!+"/"+name);
            let model = Model(name,bookSize)
            model.isdel = false
            model.date = String(format: "%f", arguments: [Date.currentTime])
            EBookDefault.setString(bookSize, "size"+name)
            return model
        }
    }
    
    static func getFilesBytesByPath(_ path:String) ->String {
        var sumSize:NSInteger = 0
        var isDirectory: UnsafeMutablePointer<ObjCBool>?
        if FileManager.default.fileExists(atPath: path, isDirectory: isDirectory) {
            sumSize = NSInteger(getSize(path))
        }
        return transBytes(sumSize)
    }
    
    static func transBytes(_ sumSize:NSInteger = 0) ->String {
        var str:String = ""
        var tempSize = sumSize
        if sumSize < 1024 {
            str = str.appendingFormat("%d B", sumSize)
        }else if sumSize > 1024 && sumSize < 1024*1024 {
            tempSize = tempSize/1024
            str = str.appendingFormat("%d Kb", tempSize)
        }else if sumSize > 1024*1024 && sumSize < 1024*1024*1024 {
            tempSize = tempSize/1024/1024
            str = str.appendingFormat("%d Mb", tempSize)
        }
        return str
    }
    
    static func getSize(_ path: String)->UInt64 {
        var fileSize : UInt64 = 0
        do {
            let attr = try FileManager.default.attributesOfItem(atPath: path)
            fileSize += attr[FileAttributeKey.size] as! UInt64
        } catch {
            print("Error: \(error)")
        }
        return fileSize
    }
    
    static func moveDatabase() throws {
        if let toPath = Tools.epubInfoSqlite() {
            if !FileManager.default.fileExists(atPath: toPath) {
                if let sqlPath = Bundle.main.path(forResource: "epubInfo", ofType: "sqlite"){
                    // try! FileManager.default.copyItem(atPath: sqlPath, toPath: toPath)
                    do {
                        try FileManager.default.copyItem(atPath: sqlPath, toPath: toPath)
                    } catch {
                        print("Error: \(error)")
                    }
                }
            }
        }
    }
    
    static func moveFile(_ fromPath:String, _ toPath:String) {
        if !FileManager.default.fileExists(atPath: toPath) {
            try! FileManager.default.copyItem(atPath: fromPath, toPath: toPath)
        }
    }
}
